package com.zrrd.sort;

import java.util.Arrays;

public class BubbleSort {
    public void bubbleSort(int[] array) {
        int temp;
        for (int i = 0; i < array.length - 2; i++) {
            for (int j = 0; j + 1 < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

    public void bubbleSortOptimized(int[] array) {
        int temp;
        boolean flag = false;
        for (int i = 0; i < array.length - 2; i++) {
            for (int j = 0; j + 1 < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    flag = true;
                }
            }
            if (!flag) {
                return;
            }

        }
    }

    public static void main(String[] args) {
        BubbleSort bubbleSort = new BubbleSort();
        int[] arr = new int[]{2, 44, 5, 11, 33, 29, 45};
        bubbleSort.bubbleSortOptimized(arr);
        System.out.println(Arrays.toString(arr));
    }
}
